<template>
  <CompOperate
      :field="field"
      :designer="designer"
      :design-state="designState"
      :parent-list="parentList"
      :parent-widget="parentWidget"
      :sub-form-row-id="subFormRowId"
      :sub-form-row-index="subFormRowIndex"
      :sub-form-col-index="subFormColIndex"
      :index-of-parent-list="indexOfParentList"
      :display-style="field['options'].displayStyle"
  >
    <div class="scene-picture-1080" :style="getStyle('head')" ref="el" :data-info="sourceShown">
      <!--含有视频-->
      <template v-if="sourceShown">
        <template v-if="!devType" data-info="测试环境">
          <template v-if="(sourceFilter?.length) ===1">
            <div class="swiper-container">
              <div class="swiper-wrapper">
                <template v-for="(item,index) in (optionsInfo.carouselInfo)">
                  <div class="swiper-slide">
                    <img
                        class="picture"
                        alt="图片资源"
                        :class="{'fill': optionsInfo?.fill}"
                        :src="getPictureSource(item.url)"
                    />
                  </div>
                </template>
              </div>
              <div class="swiper-pagination"></div>
            </div>
          </template>
          <template v-else>
            <template v-if="mounted">
              <div class="swiper-container" ref="swiper" :key="carouselKey">
                <van-swipe
                    class="swiper-wrapper"
                    :autoplay="5000"
                    :loop="true"
                    ref="swiperInfo"
                    :touchable="true"
                    :stop-propagation="false"
                    indicator-color="white"
                    @change="handleSwiperChange">
                  <template v-for="(item,index) in sourceFilter">
                    <van-swipe-item class="swiper-slide">
                      <img
                          @dragstart.prevent
                          :key="index"
                          class="picture"
                          alt="图片资源"
                          :src="getPictureSource(item.url)"
                          :class="{'fill': optionsInfo?.fill}"
                      />
                    </van-swipe-item>
                  </template>
                  <template #indicator>
                    <div class="custom-indicator">{{ current }}/{{ (sourceFilter?.length) }}</div>
                  </template>
                </van-swipe>
                <template v-if="false">
                  <div class="swiper-wrapper">
                    <template v-for="(item,index) in (optionsInfo.carouselInfo)">
                      <div class="swiper-slide"
                           :data-swiper-autoplay="`${(item.delay || 5)*1000}`"
                           v-swiper='{
                          current:index,
                          length:(optionsInfo?.carouselInfo?.length)
                      }'
                      >
                        <img
                            class="picture"
                            alt="图片资源"
                            :src="getPictureSource(item.url)"
                            :class="{'fill': optionsInfo?.fill}"
                        />
                      </div>
                    </template>
                  </div>
                  <div class="swiper-pagination"></div>
                </template>
              </div>
            </template>
          </template>
        </template>
      </template>
      <template v-else>
        <template v-if="!!(sourceFilter?.length)">
          <template v-if="(sourceFilter?.length) ===1">
            <div class="swiper-container">
              <div class="swiper-wrapper">
                <template v-for="(item,index) in (optionsInfo.carouselInfo)">
                  <div class="swiper-slide">
                    <img
                        class="picture"
                        alt="图片资源"
                        :class="{'fill': optionsInfo?.fill}"
                        :src="getPictureSource(item.url)"
                    />
                  </div>
                </template>
              </div>
              <div class="swiper-pagination"></div>
            </div>
          </template>
          <template v-else>
            <template v-if="mounted">
              <div class="swiper-container" ref="swiper" :key="carouselKey">
                <van-swipe
                    class="swiper-wrapper"
                    :autoplay="5000"
                    :loop="true"
                    ref="swiperInfo"
                    :touchable="true"
                    :stop-propagation="false"
                    indicator-color="white"
                    @change="handleSwiperChange">
                  <template v-for="(item,index) in sourceFilter">
                    <van-swipe-item class="swiper-slide">
                      <img
                          @dragstart.prevent
                          :key="index"
                          class="picture"
                          alt="图片资源"
                          :src="getPictureSource(item.url)"
                          :class="{'fill': optionsInfo?.fill}"
                      />
                    </van-swipe-item>
                  </template>
                  <template #indicator>
                    <div class="custom-indicator">{{ current }}/{{ (sourceFilter?.length) }}</div>
                  </template>
                </van-swipe>
                <template v-if="false">
                  <div class="swiper-wrapper">
                    <template v-for="(item,index) in (optionsInfo.carouselInfo)">
                      <div class="swiper-slide"
                           :data-swiper-autoplay="`${(item.delay || 5)*1000}`"
                           v-swiper='{
                          current:index,
                          length:(optionsInfo?.carouselInfo?.length)
                      }'
                      >
                        <img
                            class="picture"
                            alt="图片资源"
                            :src="getPictureSource(item.url)"
                            :class="{'fill': optionsInfo?.fill}"
                        />
                      </div>
                    </template>
                  </div>
                  <div class="swiper-pagination"></div>
                </template>
              </div>
            </template>
          </template>
        </template>
      </template>
    </div>
  </CompOperate>
</template>

<script>
import "@vant/touch-emulator"
import {v4 as uuid} from "uuid";
import {pxToVw} from "@/utils/common";
import emitter from "@/utils/designer/emitter";
import mixin from "@sc/templateDetails/modules/homeMiddle/fieldMixin";
import CompOperate from "@c/public/form-designer/devType/modules/compOperate.vue";
import {buildParentApi} from "@/utils/designer/util";

export default {
  name: "scene-picture-1080-widget",

  componentName: "FieldWidget", //必须固定为FieldWidget，用于接收父级组件的broadcast事件

  mixins: [emitter, mixin],

  components: {
    CompOperate,
  },

  props: {
    widget: Object,
    field: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    designer: Object,
    designState: {
      type: Boolean,
      default: false,
    },
    devType: {
      type: Boolean,
      default: false,
    },

    subFormRowIndex: {
      /* 子表单组件行索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormColIndex: {
      /* 子表单组件列索引，从0开始计数 */ type: Number,
      default: -1,
    },
    subFormRowId: {
      /* 子表单组件行Id，唯一id且不可变 */ type: String,
      default: "",
    },

    headTitle: {
      type: String,
      default: "",
    },
    visibleTitle: {
      type: Boolean,
    },
    //prop传入的表单JSON配置
    parentApi: {
      type: Object,
      default: () => buildParentApi()
    },
  },

  data() {
    return {
      current: 1,
      mounted: false,
      optionsInfo: Array(),
      carouselKey: uuid(),
      swiperPicture: [1, 2, 3, 4, 5, 6],
      header: require("@a/images/design/header-03.jpg"),
    }
  },

  computed: {
    //生成唯一的字符串
    getOnlyId() {
      return function () {
        return uuid()
      }
    },

    // 模板的行内样式
    getStyle() {
      return function (val) {
        const self = this;
        let info = (self.optionsInfo) || Object();
        let Obj = Object();
        switch (val) {
          case "head":
            Reflect.set(Obj, "height", pxToVw(info.height));
            return Obj;
        }
      };
    },

    // 获取图片资源
    getPictureSource() {
      return function (row) {
        return `${row}?t=${this.getOnlyId()}`
      }
    },

    sourceFilter() {
      let {carouselInfo} = this.optionsInfo;
      const videoExtensions = ['mp4', 'avi', 'wmv', 'flv', '3gp', 'mpg', 'rmvb', 'swf'];
      return this.$lodash.filter(carouselInfo, (item) => {
        return !(videoExtensions.includes((item?.type)))
      })
    },

    sourceShown() {
      let {carouselInfo} = this.optionsInfo;
      const videoExtensions = ['mp4', 'avi', 'wmv', 'flv', '3gp', 'mpg', 'rmvb', 'swf'];
      let types = this.$lodash.map(carouselInfo, 'type');
      const result = this.$lodash.intersection(videoExtensions, types);
      return !!(result?.length)
    }

  },

  mounted() {
    this.handleOnMounted();
    this.$nextTick(() => {
      this.mounted = true;
      this.executeMethod('getVideoMedias',null);
    });
  },

  methods: {
    handleSwiperChange(index) {
      let {carouselInfo} = this.optionsInfo;
      this.current = ++index;
      if (this.current === carouselInfo.length) {
        this.$refs?.swiperInfo?.resize()
      }
    },

    // 接收父组件传递过来的数据
    async executeMethod(key) {
      switch (key) {
          //   关于有视频不分由安卓端负责播放
        case "getVideoMedias":
          let {carouselInfo, swiperTime = 10} = this.optionsInfo;

          // 是否与视频有重叠
          let overlap = this.sourceShown;
          if (overlap) {
            let element = (this.$refs.el);
            if (element) {
              let params = Object();
              const rect = element.getBoundingClientRect();
              const positionInfo = {
                width: Math.ceil(rect.width),
                height: Math.ceil(rect.height),
                top: parseInt(rect.top),
                right: parseInt(rect.right),
                bottom: parseInt(rect.bottom),
                left: parseInt(rect.left),
                time: swiperTime,
              };
              Reflect.set(params, 'positionInfo', positionInfo);
              Reflect.set(params, 'video', carouselInfo);
              this.parentApi?.executeParentMethod('playVideoMedias', params);
            }
          } else {
            return false
          }
          break
      }
    }
  },

  destroyed() {
    this.unregisterFromRefList();
    this.mounted = false;
  },

  watch: {
    // 获取配置项
    field: {
      handler: function (val) {
        let key = (val.options.config);
        this.carouselKey = uuid();
        this.optionsInfo = val?.options[key] || Object();
      },
      deep: true,
      immediate: true
    },


    mounted: {
      handler: function (val, pre) {
        if (val && val !== pre) {
          this.$nextTick(() => {
            this.$refs?.swiperInfo?.resize()
          })
        }
      },
      deep: true,
      immediate: true
    }
  },

}
;
</script>

<style lang="scss" scoped>
.scene-picture-1080 {
  background-color: transparent;
  color: #333;
  height: 100%;
  line-height: 100%;
  flex-direction: column;

  .swiper-container {
    height: 100%;
    width: 100%;

    .swiper-slide {
      width: 100%;
      height: 100%;
      font-size: 38px;
      line-height: 76px;
      text-align: center;
      align-items: center;


      .picture {
        width: 100% !important;
        height: 100% !important;
        object-fit: contain !important;
      }

      .fill {
        width: 100% !important;
        height: 100% !important;
        object-fit: cover !important;
        object-position: center; /* 图片居中显示 */
      }
    }

    .swiper-wrapper {
      position: relative;

      .custom-indicator {
        display: inline-block;
        width: 100%;
        position: absolute;
        bottom: 0;
        font-size: 32px;
        line-height: 60px;
        text-align: center;
        height: 60px;
        @include fontWeight();
      }

    }


  }

}
</style>